package com.qf.web.controller;

import com.qf.pojo.Account;
import com.qf.pojo.R;
import com.qf.service.AccountService;
import com.utils.ThreadLocalUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/account")
public class AccountController {

    @Autowired
    private AccountService accountService;


    @GetMapping("/{id}")
    public R findOne(@PathVariable("id") Integer id){
        //调用service
        Account account = accountService.findById(id);

        return R.success(account);
    }

    @GetMapping
    public R findAll(){
        List<Account> accounts = accountService.findAll();

        return R.success(accounts);
    }

    @PutMapping
    public R update(Account account){
        int num = accountService.update(account);

        if (num > 0){
            return R.success("更新成功");
        }else{
            return R.success("更新失败");
        }
    }

    /**
     * 查询当前登录用户的所有账户
     * @return
     */
    @GetMapping("/user")
    public R findUserAccounts(){
        int uid = ThreadLocalUtils.getUid();

        List<Account> accounts = accountService.findByUid(uid);

        return R.success(accounts);
    }

    @PostMapping("/transfer")
    public R transfer(Integer outId,String inName,Double money){
        accountService.transfer(outId,inName,money);

        return R.success("转账成功");
    }

    @PostMapping
    public R add(@RequestBody Account account){
        int num = accountService.add(account);

        if (num > 0) {
            return R.success("新增成功");
        }else {
            return R.error("新增失败");
        }
    }

    @DeleteMapping("/{id}")
    public R delete(@PathVariable("id") Integer id){
        int num = accountService.deleteById(id);

        if (num > 0) {
            return R.success("删除成功");
        }else {
            return R.error("删除失败");
        }
    }
}
